// ref
// https://blog.csdn.net/weixin_42958308/article/details/103138163

/* --- ESC control ---*/
// arming of ESC 电调的保险
// 一开始给电调供电时, 信号值必须大于等于1ms 对应的电机会发出蜂鸣声 properly armed
// 如果刚开始信号值大于1ms, 之后信号要先低于1ms, 之后电机才会工作
#include <Servo.h>
// using <Servo.h>, we can easily produce 50Hz PWM signal
Servo ESC;  // create servo object to produce PWM signal to control the ESC

int potValue;         // value from the analog pin
String command = "";  // 接收无线数传数据

void setup() {
  // attach(pin, min pulse width, max pulse width)
  ESC.attach(9, 1000, 2000);
  // 在这里定义好脉冲宽度的范围 1000-2000us(micoseconds)
  // potentiometer connected to pin 9

  Serial.begin(9600);
  Serial.println("Serial monitor starts successfully!");
}

void loop() {
  // potValue = analogRead(A0);
  // potValue = map(potValue, 0, 1023, 0, 180);
  // send signal to ESC
  // 0-180 refer to 1000-2000 defined before


  while (Serial.available() > 0) {
    command += char(Serial.read());
    delay(2);
  }
  // if (command.length() > 0) {
  //   if (command == "123") {
  //     Serial.println(command);
  //     Serial.write("successfully write dataaaaa");
  //     for (int i = 1500; i <= 2000; i += 100) {
  //       ESC.write(i);
  //       delay(2000);
  //     }
  //   }
  //   Serial.println(command);
  //   Serial.write("successfully write data");
  //   // Serial.println("successfully write data");
  //   command = "";
  // }
  int x_placeinstring = 0;
  int y_placeinstring = 0;
  int z_placeinstring = 0;
  String x_command;
  String y_command;
  String z_command;
  int x_int;
  int y_int;
  int z_int;
  if (command.length() > 0) {
    Serial.println(command);
    x_placeinstring = command.indexOf('x');
    y_placeinstring = command.indexOf('y');
    z_placeinstring = command.indexOf('z');
    x_command = command.substring(x_placeinstring + 1, y_placeinstring);
    y_command = command.substring(y_placeinstring + 1, z_placeinstring);
    z_command = command.substring(z_placeinstring + 1);
    x_int = x_command.toInt();
    y_int = y_command.toInt();
    z_int = z_command.toInt();
    Serial.println(x_int);
    Serial.println(y_int);
    Serial.println(z_int);
    if (x_int == 1)
      for (int i = 1500; i <= 2000; i += 100) {
        ESC.write(i);
        delay(2000);
      }
      for (int i = 2000; i >= 1000; i -= 100) {
        ESC.write(i);
        delay(2000);
      }
      //   delay(2000);
      // ESC.write(500);
      //   delay(2000);
      // ESC.write(1000);
    command = ""; 
  }
}